<template>
  <div id="app">
    <h1>{{title}}</h1>
    <ul class="todos">
      <li>
        <input v-model="newToDo" placeholder="请输入你准备做的事情" @keyup.13="addToDo" autofocus="true" />
      </li>
      <li v-for="(todo,index) in todos" :key="index" :id="index" :class="{'checked':todo.done}">
        <input type="checkbox" @change="saveToStore" v-model="todo.done" />
        <label>{{index+1}}.{{todo.value}}</label>
        <time>{{todo.created | date}}</time>
        <button @click="delToDo(todo)"></button>
      </li>
    </ul>
  </div>
</template>

<script>
import './assets/site.less'
import './assets/todos.less'
import moment from 'moment'
import 'moment/locale/zh-cn'

moment.locale('zh-cn')

export default {
  name: 'App',
  data () {
    return {
      title: 'vue-todos',
      todos: [
        {
          value: '阅读一本关于前端开发的书',
          created: Date.now(),
          done: true
        }
      ],
      newToDo: ''
    }
  },
  filters: {
    date (val) {
      return moment(val).calendar()
    }
  },
  created () {
    if (this.is_initialized()) {
      this.todos = JSON.parse(localStorage.getItem('vue-todos'))
    }
  },
  computed: {
    is_initialized () {
      return localStorage.getItem('vue-todos') != null
    }
  },
  methods: {
    addToDo () {
      this.todos.push({
        value: this.newToDo,
        created: Date.now(),
        done: false
      })
      this.saveToStore()
      this.newToDo = ''
    },
    delToDo (todo) {
      this.todos = this.todos.filter((x) => x !== todo
      )
      this.saveToStore()
    },
    saveToStore () {
      localStorage.setItem('vue-todos', JSON.stringify(this.todos))
    }
  }
}
</script>

<style>

</style>
